import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

/**
 * 主题管理Store
 * 统一管理整个应用的暗黑模式状态
 */
export const useThemeStore = defineStore('theme', () => {
  // 当前是否为暗黑模式
  const isDark = ref(false)

  /**
   * 初始化主题（从localStorage恢复）
   */
  const initTheme = () => {
    const savedTheme = localStorage.getItem('theme')
    const htmlElement = document.documentElement
    
    if (savedTheme === 'dark') {
      isDark.value = true
      htmlElement.classList.add('dark')
    } else {
      isDark.value = false
      htmlElement.classList.remove('dark')
    }
  }

  /**
   * 切换主题
   */
  const toggleTheme = () => {
    isDark.value = !isDark.value
    applyTheme()
  }

  /**
   * 设置主题（直接设置为浅色或深色）
   * @param {'light' | 'dark'} theme 
   */
  const setTheme = (theme) => {
    isDark.value = theme === 'dark'
    applyTheme()
  }

  /**
   * 应用主题到DOM
   */
  const applyTheme = () => {
    const htmlElement = document.documentElement
    
    if (isDark.value) {
      htmlElement.classList.add('dark')
      localStorage.setItem('theme', 'dark')
    } else {
      htmlElement.classList.remove('dark')
      localStorage.setItem('theme', 'light')
    }
  }

  // 监听主题变化，实时应用
  watch(isDark, () => {
    applyTheme()
  })

  return {
    isDark,
    initTheme,
    toggleTheme,
    setTheme
  }
})

